package com.ruoyi.api.gd;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ruoyi.api.ThirdPartyApi;
import com.ruoyi.api.resp.ApiResponse;
import com.ruoyi.config.GdApiConfig;
import com.ruoyi.entity.WeatherData;
import com.ruoyi.enums.GDApiRequestUrlEnum;
import com.ruoyi.mapper.WeatherDataMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Service
public class GaoDeWeatherApi implements ThirdPartyApi {

    private final GdApiConfig gdApiConfig;

    @Autowired
    WeatherDataMapper mapper;

    public GaoDeWeatherApi(GdApiConfig gdApiConfig) {
        this.gdApiConfig = gdApiConfig;
    }

    @Override
    public ApiResponse<WeatherData> getWeatherData(String code) {
        String url = GDApiRequestUrlEnum.WEATHER_FORECAST.getUrl();
        String params = "key=" + gdApiConfig.getKey() + "&city=" + code;
        String response = HttpUtil.get(url + "?" + params);
        JSONObject jsonObject = JSONUtil.parseObj(response);
        if ("1".equals(jsonObject.getStr("status"))) {
            JSONObject liveData = jsonObject.getJSONArray("lives").getJSONObject(0);
            WeatherData weatherData = JSONUtil.toBean(liveData, WeatherData.class);
            mapper.insert(weatherData);
            return ApiResponse.success(weatherData);
        } else {
            return ApiResponse.error(jsonObject.getStr("infocode"), jsonObject.getStr("info"));
        }
    }
}

